#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "do_test.h"
#include "do_rw.h"
#include "do_config.h"
#include "unit_test.h"
#include "thread_ctrl.h"
#include "ietDoLib.h"

static struct unit_item_t unit_item[DO_ITEM_NUM];
static struct thread_param_t thread_param[DO_MAX_NUM];
static struct thread_info_t thread_info = {
    .num = DO_MAX_NUM,
    .param = thread_param,
};
static struct do_dev_t do_dev[DO_MAX_NUM];
static struct do_param_t do_param = {
    .dev = do_dev,
};
static struct do_item_t do_item = {
    .param = &do_param,
    .thread = &thread_info,
};

static void init_unit_item(struct unit_item_t *item) {
    item[0] = (struct unit_item_t){0,  "null",          "0. 退出程序",      NULL};
    item[1] = (struct unit_item_t){1,  "do_level",      "1. 电平输出",      config_do_mode_level};
    item[2] = (struct unit_item_t){2,  "do_pulse",      "2. 脉冲输出",      config_do_mode_pulse};
}

static int get_param(struct do_param_t *param) {
    struct do_item_t *punit = (struct do_item_t *)param->parent;
    struct thread_info_t *pthread_info = punit->thread;
    struct thread_param_t *pthread = pthread_info->param;
    int ret = 0;
    char input[32];
    uint8_t i = 0;

    printf("\n===== %s 设备测试程序 =====\n", DO_ITEM_NAME);
    printf("请选择测试项:\n");
    for (int i = 0; i < DO_ITEM_NUM; i++) {
        printf("%s\n", unit_item[i].text);
    }
    printf("请输入选择 (输入数字): ");
    if (fgets(input, sizeof(input), stdin) == NULL) {
        return -1;
    }
    if (pthread->exit_sig) {
        param->item_id = 0;
        return 0;
    }
    param->item_id = atoi(input);
    if (param->item_id == 0)
        return 0;
    if (unit_item[param->item_id].config != NULL) {
        unit_item[param->item_id].config(param);
    }

    printf("请输入%s通道号 (0-%d): ", DO_ITEM_NAME, param->max_num - 1);
    if (fgets(input, sizeof(input), stdin) == NULL) {
        return -1;
    }
    if (pthread->exit_sig) {
        param->item_id = 0;
        return 0;
    }
    input[strcspn(input, "\n")] = '\0';
    if (strlen(input) == 0) {
        param->dev_id = param->max_num;
    } else {
        param->dev_id = atoi(input);
    }
    if (param->dev_id >= param->max_num) {
        param->dev_id = 0;
        for (i = param->dev_id; i < (param->dev_id + param->dev_num); i++) {
            param->dev[i].index = i;
        }
    } else {
        param->dev_num = 1;
        param->dev[param->dev_id].index = param->dev_id;
    }

    switch (param->item_id) {
    case 1:
        printf("请输入电平(0/1): ");
        if (fgets(input, sizeof(input), stdin) == NULL) {
            return -1;
        }
        if (pthread->exit_sig) {
            param->item_id = 0;
            return 0;
        }
        param->set_val = atoi(input);
        for (i = param->dev_id; i < (param->dev_id + param->dev_num); i++) {
            param->dev[i].set_val = param->set_val;
        }
        // printf("set_val=%d dev_num=%d dev[%d].set_val=%d\n", 
        //        param->set_val, param->dev_num, param->dev_id, param->dev[param->dev_id].set_val);
        break;
    default:
        break;
    }

    return ret;
}

int do_test(int argc, char *argv[])
{
    struct thread_param_t *pthread = &thread_param[0];
    struct do_param_t *pparam = &do_param;
    struct do_dev_t *pdev= &pparam->dev[0];
    int ret = 0;
    uint8_t i = 0;
    uint8_t thread_cnt = 0;
    pthread_t sig_tid;

    do_item.thread = &thread_info;
    do_item.thread->param = &thread_param[0];
    do_item.param = &do_param;
    do_item.param->dev_num = DO_MAX_NUM;
    do_item.param->dev = &do_dev[0];
    do_param.parent = &do_item;
    do_param.dev = &do_dev[0];
    for (i = 0; i < DO_MAX_NUM; i++) {
        do_dev[i].parent = (void *)do_item.param;
    }

    init_process_signal_handle(&sig_tid, signal_handler_thread, do_item.thread);
    init_unit_item(unit_item);

    while (!pthread->exit_sig) {
        if (get_module_type(&pparam->type) < 0) {
            printf("无效选择，请重新输入\n");
            sleep(2);
            continue;
        } else {
            break;
        }
    }
    pparam->dev_num = get_dev_num(DO_DRV_NAME);
    pparam->max_num = pparam->dev_num;
    printf("Get %s device number %d\n", DO_DRV_NAME, pparam->dev_num);
    while (!pthread->exit_sig) {
        thread_cnt = 0;
        // do_param.dev_num = DO_MAX_NUM;

        if (argc > 2) {
            for(i = 0; i < argc; i++) {
                printf("%s ", argv[i]);
            };
            printf("\n");
            return EXIT_FAILURE;
        } else {
            if (0 != get_param(pparam)) {
                printf("无效选择，请重新输入\n");
                sleep(2);
                continue;
            }
            if (0 == pparam->item_id) {
                printf("程序退出\n");
                break;
            }
        }

        if (unit_item[pparam->item_id].config != NULL) {
            printf("\n测试项 %d 正在执行\n", pparam->item_id);
            ret = DOMOpen(pparam->type);
            if (ret < 0) {
                fprintf(stderr, "Open DO device failed\n");
                return ret;
            }
            printf("DOMGetDrvVer v%d.%d\n", ((DOMGetDrvVer() >> 8) & 0xFF), (DOMGetDrvVer() & 0xFF));
            printf("DOMGetFpgaVer v%d.%d\n", ((DOMGetFpgaVer() >> 8) & 0xFF), (DOMGetFpgaVer() & 0xFF));
            printf("DOMGetLibVer v%d.%d\n", ((DOMGetLibVer() >> 8) & 0xFF), (DOMGetLibVer() & 0xFF));
            for (i = pparam->dev_id; i < (pparam->dev_id + pparam->dev_num); i++) {
                pdev = &pparam->dev[i];
                if (pparam->en_write == 1) {
                    pdev->write_thread = &pthread[thread_cnt];
                    snprintf(pthread[thread_cnt].name, sizeof(pthread[thread_cnt].name), "%s%s%d", "send_", pparam->name, pdev->index);
                    if (pthread_create(&pthread[thread_cnt].id, NULL, send_do_thread, pdev) != 0) {
                        fprintf(stderr, "Create %s receive thread failed\n", pdev->path);
                    } else {
                        // printf("Create %s receive thread success\n", pdev->path);
                    }
                    thread_cnt++;
                    usleep(5000);
                }
            }
            for (i = 0; i < thread_cnt && !pthread->exit_sig; i++) {
                pthread_join(pthread[i].id, NULL);
            }
            DOMClose();

            if (pthread->exit_sig) {
                printf("测试项 %d 用户取消\n", pparam->item_id);
            } else {
                printf("测试项 %d 执行完成\n", pparam->item_id);
            }
        } else {
            printf("测试项 %d 尚未实现\n", pparam->item_id);
            sleep(2);
        }

        thread_cnt = 0;
    }

    printf("%s return\n", __func__);

    return ret;
}
